package com.nl.orderpay;

import com.nl.bean.input.OrderEvent;
import com.nl.bean.output.OrderResult;
import java.util.List;
import java.util.Map;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

/**
 * @author shihb
 * @date 2019/12/26 12:45
 * 订单超时15分钟
 */
public class OrderTimeout {

  public static void main(String[] args) throws Exception {
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setParallelism(1);
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
    //1.订单事件流
    DataStreamSource<String> source = env.readTextFile(OrderTimeout.class.getClassLoader().getResource("OrderLog.csv").getPath());
    KeyedStream<OrderEvent, Long> eventStream = source
        .map(new MapFunction<String, OrderEvent>() {

          @Override
          public OrderEvent map(String s) throws Exception {
            String[] arr = s.split(",");
            return new OrderEvent(Long.parseLong(arr[0].trim()), arr[1].trim(), arr[2].trim(),
                Long.parseLong(arr[3].trim()));
          }
        })
        .assignTimestampsAndWatermarks(
            new BoundedOutOfOrdernessTimestampExtractor<OrderEvent>(Time.seconds(0)) {
              @Override
              public long extractTimestamp(OrderEvent element) {
                return element.getEventTime() * 1000;
              }
            }
        )
        .keyBy(orderEvent -> orderEvent.getOrderId());
    //2.定义一个模式
    Pattern<OrderEvent, OrderEvent> orderPattern = Pattern.<OrderEvent>begin("start")
        .where(new SimpleCondition<OrderEvent>() {
          @Override
          public boolean filter(OrderEvent orderEvent) throws Exception {
            return "create".equals(orderEvent.getEventType().toLowerCase());
          }
        }).followedBy("follow").where(new SimpleCondition<OrderEvent>() {
          @Override
          public boolean filter(OrderEvent orderEvent) throws Exception {
            return "pay".equals(orderEvent.getEventType().toLowerCase());
          }
        }).within(Time.minutes(15));

    //3.模式应用 得到 pattern stream
    PatternStream<OrderEvent> patternStream = CEP.pattern(eventStream, orderPattern);

    //4.调用select方法,提取匹配的事件，和超时事件
    // 定义超时的侧输出流
    OutputTag<OrderResult> timeoutOrderTag = new OutputTag<OrderResult>("timeoutOrder"){};
    SingleOutputStreamOperator<OrderResult> resultStream = patternStream
        // 侧输出流 超时事件 匹配事件
        .select(timeoutOrderTag, new OrderTimeoutSelect(), new OrderPaySelect());

    resultStream.print("pay");
    resultStream.getSideOutput(timeoutOrderTag).print("timeout");
    env.execute("order state job");

  }

}
/**
 *自定义超时事件序列处理函数
 */
class OrderTimeoutSelect implements PatternTimeoutFunction<OrderEvent, OrderResult> {

  @Override
  public OrderResult timeout(Map<String, List<OrderEvent>> map, long l) throws Exception {
    return new OrderResult(map.get("start").iterator().next().getOrderId(),"order timeout.");
  }
}
/**
 *自定义正常支付事件序列处理函数
 */
class OrderPaySelect implements PatternSelectFunction<OrderEvent, OrderResult> {

  @Override
  public OrderResult select(Map<String, List<OrderEvent>> map) throws Exception {
    // 这里用start 用follow都可以
    return new OrderResult(map.get("follow").iterator().next().getOrderId(),"order pay succeed.");
  }
}
